#include "histomgram.h"

Histomgram::Histomgram()
{
}

Histomgram::Histomgram(int *grayInfo, int threshold, Qt::GlobalColor color)
{
    m_maxPixels = 0;
    for (int i = 0; i < 256; i++)
    {
        m_grayInfo[i] = grayInfo[i];
        m_maxPixels = m_maxPixels > grayInfo[i] ? m_maxPixels : grayInfo[i];
    }
    m_threshold2 = threshold;

    m_width = 800;
    m_height = 500;
    m_threshold1 = 0;
    m_color = color;

    createImage();
}

QImage Histomgram::getImage()
{
    return m_image;
}

void Histomgram::setThreshold1(int threshold)
{
    m_threshold1 = threshold;
}

void Histomgram::setThreshold2(int threshold)
{
    m_threshold2 = threshold;
}

void Histomgram::createImage()
{
    m_image = QImage(m_width + 20, m_height + 20, QImage::Format_ARGB32);

    QPainter painter;
    painter.begin(&m_image);
    painter.drawRect(0, 0, m_width, m_height);

    QBrush brush(Qt::black);
    QPen pen(brush, 3);
    painter.setPen(pen);
    //draw the x axis
    painter.drawLine(20, 480, 791, 480);
    //draw the y axis
    painter.drawLine(20, 20, 20, 480);

    pen.setBrush(m_color);
    pen.setWidth(2);
    painter.setPen(pen);
    int x = 21;
    for (int i = 0; i < 256; i++)
    {
        int h = m_grayInfo[i] * 440 / m_maxPixels;
        painter.drawRect(x, 480 - h, 2, h);
        x = x + 3;
    }
    painter.end();

    m_source = QImage(m_image);
    drawThreshold();
}

void Histomgram::drawThreshold()
{
    m_image = QImage(m_source);

    QPainter painter;
    painter.begin(&m_image);

    QBrush brush(Qt::red);
    QPen pen(brush, 4);
    painter.setPen(pen);
    painter.drawRect(20 + 3 * m_threshold1, 20,
                     1 + 3 * (m_threshold2 - m_threshold1), 460);

    painter.end();
}
